
#include <iostream>
#include <fstream>

using namespace std;

static string appname;
static string val;

int check_params(int argc, char **argv) {
    // 对主程序转换为程序名称
    string filepath = argv[0];
    appname = filepath;
    if (filepath.find_last_of("/\\") != std::string::npos) {
        appname = filepath.substr(filepath.find_last_of("/\\")+1);
    }

    if (argc < 2) {
        cout << 
        "Usage: " << appname << " <brightness> \n" << 
        "  brightness >= 5 and brightness <= 100" << endl;;
        return 1;
    }

    val = argv[1];

    // 当亮度值 小于 5 或大于 100 时不进行动作
    int v = atoi(argv[1]);
    if (v < 5 || v > 100) {
        cout << 
        "Usage: " << appname << " <brightness> \n" << 
        "  brightness >= 5 and brightness <= 100" << endl;
        return 1;
    }
    
    return 0;
}

int	main(int argc, char **argv)
{
    // 0. 检查应用程序参数规范并处理参数初始化
    if (check_params(argc, argv)) {
        return 1;
    }

    // AMD: /sys/class/backlight/amdgpu_bl0/brightness

    // 1. 打开 AMD 核显背光设置
    fstream brightness;
    brightness.open("/sys/class/backlight/amdgpu_bl0/brightness");

    // 2.检查是否已打开
    if (!brightness.is_open()) {
        cout << "打开文件失败:\n   /sys/class/backlight/amdgpu_bl0/brightness" << endl;
        return 1;
    }

    // 3. 获取旧值
    string oldval;
    brightness >> oldval;

    // 4. 写入亮度值
    brightness << val; 
    printf("写入新值:\n  %s(旧) > %s(新)\n", oldval.c_str(), val.c_str());

    // 5. 关闭文件
    brightness.close();

    return 0;
}
